# -*- coding:utf-8 -*-
from django.http import Http404
from rest_framework.views import exception_handler
from .response import ErrorResponse

import logging
import traceback

from django.db.models import ProtectedError
from rest_framework import exceptions
from rest_framework.exceptions import APIException as DRFAPIException, AuthenticationFailed
from rest_framework.views import set_rollback

logger = logging.getLogger(__name__)


def CustomExceptionHandler(ex, context):
    # 统一异常拦截处理
    # 目的:(1)取消所有的500异常响应,统一响应为标准错误返回
    #     (2)准确显示错误信息
    # :param ex:
    # :param context:
    # :return:
    msg = ''
    code = 500

    # 权限认证（数据和菜单权限，token）
    if isinstance(ex, AuthenticationFailed):
        code = 401
        msg = ex.detail

    # 404 异常（数据查询不到等等）
    elif isinstance(ex, Http404):
        code = 404
        msg = "无当前数据，或已被删除"

    # DRF 的异常
    elif isinstance(ex, DRFAPIException):
        set_rollback()
        msg = ex.detail

    # API 处理异常
    elif isinstance(ex, exceptions.APIException):
        set_rollback()
        msg = ex.detail
    elif isinstance(ex, ProtectedError):
        set_rollback()
        msg = "删除失败"
    # elif isinstance(ex, DatabaseError):
    #     set_rollback()
    #     msg = "接口服务器异常,请联系管理员"
    elif isinstance(ex, Exception):
        logger.error(traceback.format_exc())
        msg = str(ex)

    return ErrorResponse(msg=msg, code=code)


"""
自定义rest_framework异常抛出返回格式
"""

token_message = ["token已失效", "token认证失败", "非法的token", "没有传token"]


def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)
    try:
        message = response.data["detail"]
        if response:
            if message in token_message:
                return ErrorResponse(code=401, msg=response.data["detail"])
            return ErrorResponse(msg=response.data["detail"])
    except KeyError:
        msg = "detail没有东西哇"
        return ErrorResponse(msg=msg)
